//
//  PersonalCenterViewController.m
//  减肥,美容老中医偏方
//
//  Created by appying_wxj on 14/12/12.
//  Copyright (c) 2014年 陈朕. All rights reserved.
//

#import "PersonalCenterViewController.h"
#import "CollectViewController.h"

#import "UMFeedback.h"// 友盟意见反馈的界面

@interface PersonalCenterViewController ()

@end

@implementation PersonalCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //        self.title = @"妇科偏方";
        UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, boundswidth-120, 44)];
        navLabel.text = @"我的";
        navLabel.textColor = [UIColor whiteColor];
        navLabel.font = [UIFont systemFontOfSize:18];
        navLabel.textAlignment = NSTextAlignmentCenter;
        self.navigationItem.titleView = navLabel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    self.view.backgroundColor = [UIColor whiteColor];
    [self personalCenterInitUI];
    //    [self getFilePath];
}
// 搭建个人中心的界面
-(void)personalCenterInitUI{
    //    for (int i = 0; i<总共的行数; i++) {
    //
    //        btn.frame = (按钮的起始坐标x+i%总数*（按钮宽+横向按钮间隔），按钮的起始坐标y+i/总数*（按钮高+纵向按钮的间隔），宽，高）
    //
    //    }
//    BOOL isiPhone6 = CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(750, 1134));
//    BOOL isiPhone6Plus = CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(1242, 2208));
        NSArray *imageArr = [[NSArray alloc] initWithObjects:@"image_shoucangs",@"image_clear",@"image_fankui",@"image_update", nil];
    for (int i = 0 ; i < imageArr.count ; i ++) {
        UIButton *mainButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [mainButton setTitle:[imageArr objectAtIndex:i] forState:UIControlStateNormal];
        [mainButton setBackgroundImage:[UIImage imageNamed:[imageArr objectAtIndex:i]] forState:UIControlStateNormal];
        mainButton.backgroundColor = [UIColor clearColor];
        BOOL isiPhone4 = CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 960));
//        BOOL isiPhone6Plus = CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(1242, 2208));
//        if (isiPhone6) {
//            mainButton.frame = CGRectMake(i%2*187, 18+i/2*172, 187, 172);
//        }else if (isiPhone6Plus){
//            mainButton.frame = CGRectMake(i%2*207, 18+i/2*191, 207, 191);
//        }else{
//            mainButton.frame = CGRectMake(i%2*160, 18+i/2*148, 160, 148);
//        }
        if (isiPhone4) {
            mainButton.frame = CGRectMake(i%2*(boundswidth/2), 10+i/2*(boundsheight/4+10), boundswidth/2, boundsheight/4+25);
        }else{
            mainButton.frame = CGRectMake(i%2*(boundswidth/2), 18+i/2*(boundsheight/4+10), boundswidth/2, boundsheight/4+10);
    
        }
//        mainButton.frame = CGRectMake(i%2*(boundswidth/2), 18+i/2*(boundsheight/4+10), boundswidth/2, boundsheight/4+10);
        mainButton.tag = i + 111;
        [mainButton addTarget:self action:@selector(mainButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:mainButton];
    }
    
    // 显示缓存的lab
//    _cacheLab = [[UILabel alloc] initWithFrame:CGRectMake(50, 450, 150, 50)];
//    _cacheLab.backgroundColor = [UIColor redColor];
//    _cacheLab.text = _cacheString;
//    NSLog(@"----------------%@",_cacheLab.text);
//    _cacheLab.textColor = [UIColor blackColor];
//    [self.view addSubview:_cacheLab];
    
    
}
-(void)viewDidAppear:(BOOL)animated{
    [self getFilePath];
    [self personalCenterInitUI];
}
// 显示有多少缓存的方法
-(NSString *)getFilePath{
    
    //文件管理
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //缓存路径
    
    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    
    NSString *cacheDir = [cachePaths objectAtIndex:0];
    
    NSArray *cacheFileList;
    
    NSEnumerator *cacheEnumerator;
    
    NSString *cacheFilePath;
    
    unsigned long long cacheFolderSize = 0;
    
    cacheFileList = [fileManager subpathsOfDirectoryAtPath:cacheDir error:nil];
    
    cacheEnumerator = [cacheFileList objectEnumerator];
    
    while (cacheFilePath = [cacheEnumerator nextObject]) {
        
        NSDictionary *cacheFileAttributes = [fileManager attributesOfItemAtPath:[cacheDir stringByAppendingPathComponent:cacheFilePath] error:nil];
        
        cacheFolderSize += [cacheFileAttributes fileSize];
        
    }
    
    NSString * originalString  =[NSString stringWithFormat:@"%f",cacheFolderSize/1024.0/1024.0];
    
    _cacheString  =[NSString stringWithFormat:@"%@M",[originalString substringToIndex:4]];
    NSLog(@"---------------现在有缓存----------------%@",_cacheString);
    //单位MB
    return _cacheString;
    
}
#pragma UIButtonClick
// 按钮的点击事件
-(void)mainButtonClick:(UIButton *)sender{
    switch (sender.tag) {
        case 111:{//我的收藏
            CollectViewController *collect = [[CollectViewController alloc] init];
            [self.navigationController pushViewController:collect animated:YES];
        }
            
            break;
        case 112:{// 清除缓存
            
            dispatch_async(
                           dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                           , ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                               NSLog(@"------清除缓存-------");
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               
                           });
            _cacheLab.text = @"0";
            _finishAlert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您已成功清除缓存^_^" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
            [_finishAlert show];
        }
            
            break;
        case 113:{// 意见反馈
//            [self.navigationController pushViewController:[UMFeedback feedbackViewController]
//                                                 animated:YES];

            // 模态弹出的方法
            [self presentViewController:[UMFeedback feedbackModalViewController] animated:YES completion:nil];
        }
            
            break;
        case 114:{// 版本更新
//            NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
//            CFShow((__bridge CFTypeRef)(infoDic));
//            
//            NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
//            NSLog(@"当前的版本是%@",appVersion);
            [self onCheckVersion];
            
        }
            
            break;
            
        default:
            break;
    }
}
-(void)onCheckVersion

{

    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    
    //CFShow((__bridge CFTypeRef)(infoDic));
    
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    
    
    
    NSString *URL = @"http://itunes.apple.com/lookup?id=920275997";
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    [request setURL:[NSURL URLWithString:URL]];
    
    [request setHTTPMethod:@"POST"];
    
    NSHTTPURLResponse *urlResponse = nil;
    
    NSError *error = nil;
    
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    
    
    NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
    
    NSDictionary *dic = [results JSONValue];
    
    NSArray *infoArray = [dic objectForKey:@"results"];
    
    if ([infoArray count]) {
        
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        
        NSString *lastVersion = [releaseInfo objectForKey:@"version"];
        
        
        
        if (![lastVersion isEqualToString:currentVersion]) {
            
            //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            
            alert.tag = 10000;
            
            [alert show];
            
        }
        
        else
            
        {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            alert.tag = 10001;
            
            [alert show];
            
        }
        
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{
    
    if (alertView.tag==10000) {
        
        if (buttonIndex==1) {
            
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/lao-zhong-yi-jian-fei-mei/id920275997?mt=8"];
            
            [[UIApplication sharedApplication]openURL:url];
            
        }
        
    }
    
} 


-(void)performDismiss:(NSTimer *)timer{
    [_finishAlert  dismissWithClickedButtonIndex:0 animated:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
